<?php

class PreProcessing
{
    protected $pdo;
    protected $stemmer;
    
    public function __construct(\PDO $pdo = null)
    {
        if ($pdo == null) {
            $dsn      = 'mysql:dbname=qas_quran; host=127.0.0.1; port=3306';
            $username = 'root';
            $password = '1234';
            $options  = array(
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            ); 

            try {
                $pdo  = new \PDO($dsn, $username, $password, $options);
                $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
                $this->pdo = $pdo;
            } catch (\PDOException $e) {
                ?>
                <div class="row">
                    <div class="col-lg-12">
                        <h1 class="page-header">ERROR</h1>
                    </div>
                </div>
                <?php
                echo '<div class="alert alert-danger">Connection failed : ' . $e->getMessage().'</div>';
                exit;
            }
        } else {
            $this->pdo = $pdo;
        }

        $stemmerFactory = new \Sastrawi\Stemmer\StemmerFactory();
        $this->stemmer  = $stemmerFactory->createStemmer();
    }
    
    /* Fungsi untuk menghapus karakter
     * selain A-Z, a-z, 0-9, [spasi], -
     * @param string $text
     * @return string
     */
    function hapusKarakterKhusus($text)
    {
        //~ return preg_replace("/[^a-zA-Z0-9\' '\-]+/", "", $text);
        $text = preg_replace("/[^a-zA-Z0-9\' '\-]+/", "", $text);
        $text = str_ireplace("'", "", $text);
        
        return $text;
    }

    /*
     * Hapus Karakter yang sesuai dengan
     * kata dalam table stopwords
     * @param string $text
     * @return string $newText
     */
    function hapusStopwords($text)
    {
        $newText = '';
        $sql     = "SELECT * FROM stopwords";
        foreach ($this->pdo->query($sql) as $row) {
            $stopwords[] = $row['word'];
            $newText = str_replace($row['word'], '', $text);
        }
        
        return $newText;
    }

    public function stemming($text)
    {
        return $this->stemmer->stem($text);
    }

    function ecsStemming($text)
    {
        // $ecsStemming = new EcsStemming($this->pdo);
        // return $ecsStemming->stemmingTeks($text);
        return $this->stemmer->stem($text);
    }

    function preProses($text)
    {
        $text = $this->hapusKarakterKhusus($text);
        $text = $this->hapusStopwords($text);
        $text = $this->ecsStemming($text);
        
        return $text;
    }

    function preProsessingToArray($text)
    {
        $teks = $this->preProses($text);
        $newText = explode(' ', $teks);
        
        return $newText;
    }

}

